package cn.uncode.dal.mybatis.interceptor;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import cn.uncode.dal.datasource.DBContextHolder;

import java.util.Properties;

/**
 * 拦截器,对update使用写库,对query使用读库 Created by Juny on 2017/7/4.
 */
@Intercepts({ 
	@Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
	@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
				RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class })})
public class DBSelectorInterceptor implements Interceptor {
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		String name = invocation.getMethod().getName();
		if (name.equals("update")) {
			DBContextHolder.swithToWrite();
		}else if (name.equals("query")) {
			DBContextHolder.swithToRead();
		}else {
			DBContextHolder.swithToWrite();
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		if (target instanceof Executor) {
			return Plugin.wrap(target, this);
		}else {
			return target;
		}
			
	}

	@Override
	public void setProperties(Properties properties) {
	}
}